//导入模型
import { Book } from "../model/Book.js";
//导入
import { Op } from 'sequelize'

// 定义一个异步函数fn_list，用于处理图书列表的搜索请求
const fn_list = async (ctx, next) => {
  // 从请求的查询参数中获取关键字keyword
  const keyword = ctx.request.query.keyword;
  
  // 初始化查询条件where
  let where = {};
  
  // 如果关键字keyword存在，则设置查询条件where
  // 查询条件为书名、作者或描述中包含关键字
  if (keyword) {
    where = {
      [Op.or]: [
        { bookname: { [Op.like]: `%${keyword}%` } }, // 书名包含关键字
        { author: { [Op.like]: `%${keyword}%` } },   // 作者包含关键字
        { description: { [Op.like]: `%${keyword}%` } } // 描述包含关键字
      ]
    };
  }
  console.log(keyword);
  
  // 使用Book模型的findAll方法查询所有符合条件的图书
  const books = await Book.findAll({ where });
  
  // 设置响应体，返回成功状态码、消息和图书数据
  ctx.body = {
    code: 1000,
    msg: '获取图书成功!',
    data: books
  };  
};


//图书信息
const fn_getById = async (ctx,next)=>{
    //获取url的ID
    const id = ctx.params.id
    //查询数据库
    const book = await Book.findByPk(id)
    ctx.body = {
        code:1000,
        msg:'成功!',
        data:book
    }
}
//添加图书
const fn_add = async (ctx, next) => {
    const book = ctx.request.body
    await Book.create(book)
    ctx.body = {
      code: 1000,
      msg: '添加成功',
      data: null
    }
  }
  
  //修改图书
  const fn_updata = async (ctx, next) => {
    const id = ctx.params.id
    const book = ctx.request.body
    await Book.update(book, {
      where: {
        id: id
      }
    })
  
    ctx.body = {
      code: 1000,
      msg: '修改成功',
      data: null
    }
  }
  
  //删除图书
  const fn_delete = async (ctx, next) => {
    let id = ctx.params.id || 0
  
    await Book.destroy({
      where: {
        id: id
      }
    })
  
    ctx.body = {
      code: 1000,
      msg: '删除成功',
      data: null
    }
  }

  
  export default [
    {
      method: 'get',
      url: '/books',
      fn: fn_list
    },
    {
      method: 'get',
      url: '/books/:id',
      fn: fn_getById
    },
    {
      method: 'post',
      url: '/books',
      fn: fn_add
    },
    {
      method: 'put',
      url: '/books/:id',
      fn: fn_updata
    },
    {
      method: 'delete',
      url: '/books/:id',
      fn: fn_delete
    }
  ]

